package com.geostar.constructionland.analyse.service.geohandler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.geostar.constructionland.analyse.entity.HttpResult;
import com.geostar.constructionland.analyse.service.HttpAPIService;
import com.geostar.constructionland.analyse.service.automatic.AutomaticService;
import com.geostar.constructionland.analyse.service.automatic.CoordinateFileProxy;
import com.geostar.constructionland.analyse.service.automatic.entity.CoordinateFile;
import com.geostar.constructionland.common.entity.response.ServerResponse;
import com.geostar.constructionland.common.util.CpdetectorEncoding;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 坐标服务
 * @author yell
 * @since 2020/07/15
 */
@Service
@Slf4j
public class CoordinateService {
    @Autowired
    AutomaticService automaticService;
    @Autowired
    ObjectMapper objectMapper;
    @Autowired
    CoordinateFileProxy coordinateFileProxy;
    @Autowired
    HttpAPIService httpAPIService;
    @Autowired
    CpdetectorEncoding cpEncoding;

    @Value("${automatic.updateMultipleJsydJbxx}")
    String updateMultipleJsydJbxxUrl;
    @Value("${automatic.fileServerUrl}")
    String fileServerUrl;
    @Value("${automatic.afterImportCoordinateUrl}")
    String afterImportCoordinateUrl;

    /***
     * 坐标文件导入
     * @param multipartFiles 上传文件
     * @param ywid 业务ID
     * @param yhid 用户ID
     */
    public ServerResponse coordinateFileImport(List<MultipartFile> multipartFiles,String ywid,String yhid, String newId, String zblx) throws Exception{
        ServerResponse serverResponse = null;
        // 转换前坐标文件
        List<CoordinateFile> originalCoordinateFiles = new ArrayList<>();
        // 转换后坐标文件
        List<CoordinateFile> coordinateFiles = new ArrayList<>();
        // 坐标文件内容
        List<String> fileContentList = new ArrayList<>();
        // 坐标文件名称
        List<String> fileNameList = new ArrayList<>();
        for(MultipartFile file : multipartFiles) {
            CpdetectorEncoding cpEncoding = new CpdetectorEncoding();
            /**获取文件编码*/
            Charset charsetName = cpEncoding.getFastEncoding(file.getBytes());
            if(charsetName.name().equals("x-EUC-TW")){
                charsetName = Charset.forName("GBK");
            }
            log.info("charsetName:{}", charsetName);
            /**读取文件**/
            String content = new String(file.getBytes(),charsetName);
            log.info("content:{}",content);
            /**验证文件**/
            boolean isOk = automaticService.coordinateCheck(content);
            if(isOk){
                fileContentList.add(content);
                fileNameList.add(file.getOriginalFilename());
            }else {
                return ServerResponse.createByErrorCodeMessage(901,"文件格式出错,请检查格式。");
            }
        }
        serverResponse = executeImportCoordinates(ywid, yhid, newId, zblx, originalCoordinateFiles, coordinateFiles, fileContentList, null, fileNameList);
        return serverResponse;
    }

    /***
     * 从服务器批量导入坐标文件
     * @param fileIdNameList
     * @param ywid
     * @param yhid
     * @return
     * @throws Exception
     */
    public ServerResponse importCoordinatesFromServer(List<String> fileIdNameList, String ywid, String yhid, String newId, String zblx) throws Exception{
        ServerResponse serverResponse = null;
        if(fileIdNameList.size() > 0) {
            Map<String,Object> param = new HashMap<>();
            // 查询获取附件服务器IP及端口
            HttpResult fileServerHttpResult = httpAPIService.doPostByJsonParam(fileServerUrl, objectMapper.writeValueAsString(param));
            if(fileServerHttpResult.getCode() == 200) {
                Map<String,String> fileServerResultMap = objectMapper.readValue(fileServerHttpResult.getBody(), Map.class);
                String uploadServer = fileServerResultMap.get("uploadServer");
                // 转换前坐标文件
                List<CoordinateFile> originalCoordinateFiles = new ArrayList<>();
                // 转换后坐标文件
                List<CoordinateFile> coordinateFiles = new ArrayList<>();
                // 坐标文件内容
                List<String> fileContentList = new ArrayList<>();
                // 坐标文件ID
                List<String> fileIdList = new ArrayList<>();
                // 坐标文件名称
                List<String> fileNameList = new ArrayList<>();
                for (String fileIdName : fileIdNameList) {
                    String[] fileIdNameArr = fileIdName.split("#@#");
                    String fileId = fileIdNameArr[0];
                    String fileName = fileIdNameArr[1];
                    // 下载附件
                    String content = httpAPIService.downloadFileForContent(uploadServer +"Resource/mvc/file/fileDownload?id="+ fileId);
                    /**验证文件**/
                    boolean isOk = automaticService.coordinateCheck(content);
                    if(isOk){
                        fileContentList.add(content);
                        fileIdList.add(fileId);
                        fileNameList.add(fileName);
                    }else {
                        return ServerResponse.createByErrorCodeMessage(901,"文件格式出错,请检查格式。");
                    }
                }
                serverResponse = executeImportCoordinates(ywid, yhid, newId, zblx, originalCoordinateFiles, coordinateFiles, fileContentList, fileIdList, fileNameList);
                /** 删除本地上传的坐标附件 **/
                param.put("ywid", ywid);
                param.put("zblx", zblx);
                Map<String,Object> mapParm = new HashMap<>();
                mapParm.put("param", param);
                httpAPIService.doPostByJsonParam(afterImportCoordinateUrl, objectMapper.writeValueAsString(mapParm));
            }
        } else {
            serverResponse = ServerResponse.createByErrorMessage("导入文件为空！");
        }
        return serverResponse;
    }

    /**
     *
     * @param ywid 业务ID
     * @param yhid 用户ID
     * @param newId 新业务ID
     * @param zblx 坐标类型
     * @param originalCoordinateFiles 转换前坐标文件
     * @param coordinateFiles 转换后坐标文件
     * @param fileContentList 坐标文件内容
     * @param fileNameList 坐标文件名称
     * @return
     */
    public ServerResponse executeImportCoordinates(String ywid, String yhid, String newId, String zblx,
                                                   List<CoordinateFile> originalCoordinateFiles, List<CoordinateFile> coordinateFiles,
                                                   List<String> fileContentList, List<String> fileIdList, List<String> fileNameList) throws Exception {
        /**文件上传（若附件ID已经存在，将不再上传）**/
        if(CollectionUtils.isEmpty(fileIdList)) {
            String fileIdStr = automaticService.uploadTxtFile(fileContentList, ywid, fileNameList, zblx);
            Map<String, Object> fileIdMap = objectMapper.readValue(fileIdStr, Map.class);
            fileIdList = (List<String>) fileIdMap.get("fileIds");
            if(fileIdList.size() != fileNameList.size()) {
                return  ServerResponse.createByErrorMessage("上传文件失败!");
            }
        }
        for (int i = 0; i < fileIdList.size(); i++) {
            String fileId = fileIdList.get(i);
            /**解析坐标**/
            CoordinateFile coordinateFile = coordinateFileProxy.proxyFileContent(fileContentList.get(i));
            coordinateFile.getAllAttribute().put("fjid", fileId);
            originalCoordinateFiles.add(coordinateFile);
            /***坐标转换**/
            automaticService.coordinateTransform(coordinateFile);
            coordinateFiles.add(coordinateFile);
        }

        /**坐标文件检查**/
        HttpResult overlapHttpResult = automaticService.multipleOverlapCheck(coordinateFiles);
        log.info("重叠检测,调用状态:{},返回内容:{}",overlapHttpResult.getCode(),overlapHttpResult.getBody());
        if(overlapHttpResult.getCode()==200){
            Map<String,Object> overlapInfoMap = objectMapper.readValue(overlapHttpResult.getBody(),Map.class);
            List<Object> overlapList = (List<Object>)overlapInfoMap.get("ProcessValue");
            if(overlapList.size() > 0){
                return ServerResponse.createByErrorCodeMessage(902,"检查->有重叠");
            }
        }else {
            return ServerResponse.createByErrorCodeMessage(900,"检查->调用重叠检查SOE服务失败!!");
        }

        /**自相交监测**/
        HttpResult selfHttpResult = automaticService.multipleOriginalSelfIntersectCheck(originalCoordinateFiles);
        log.info("自相交监测,调用状态:{},返回结果{}",selfHttpResult.getCode(),selfHttpResult.getBody());
        if(selfHttpResult.getCode()==200){
            Map<String,Object> slfInfoMap = objectMapper.readValue(selfHttpResult.getBody(),Map.class);
            List<Object> slfList = (List<Object>)slfInfoMap.get("ProcessValue");
            if(slfList.size() > 0){
                return ServerResponse.createByErrorCodeMessage(903,"检查->有自相交");
            }
        }else {
            return ServerResponse.createByErrorCodeMessage(900,"检查->调用自相交SOE服务失败!!");
        }

        Map<String,String> kcdjMap = null;
        /**更新经办信息**/
        HttpResult updateJbxxResult = updateMultipleJsydJbxx(coordinateFiles,ywid,newId,yhid);
        log.info("更新建设用地经办信息,调用状态:{},返回内容:{}",updateJbxxResult.getCode(),updateJbxxResult.getBody());
        if(updateJbxxResult.getCode() == 200){
            Map<String,Object> resultMap = objectMapper.readValue(updateJbxxResult.getBody(),Map.class);
            kcdjMap = (Map<String,String>)resultMap.get("kcdjid");
            /**对每个文件进行kcdjId验证**/
            for(CoordinateFile coordinateFile : coordinateFiles){
                String fjId = coordinateFile.getAllAttribute().get("fjid").toString();
                if(!kcdjMap.containsKey(fjId) || StringUtils.isBlank(kcdjMap.get(fjId))){
                    return ServerResponse.createByErrorCodeMessage(905,"接口->更新经办信息失败!!");
                }
            }
        }else{
            return ServerResponse.createByErrorCodeMessage(905,"接口->更新经办信息失败!!");
        }

        /**
         * 导入地块信息
         */
        for (CoordinateFile coordinateFile : coordinateFiles){
            String fjId = coordinateFile.getAllAttribute().get("fjid").toString();
            String insertResult = automaticService.insertJsydDkxx(coordinateFile,kcdjMap.get(fjId),ywid);
            log.info("保存地块信息内容:{}",insertResult);
        }
        return ServerResponse.createBySuccessMessage("导入成功!");
    }

    /**
     * 更新经办信息
     * @param coordinateFiles
     * @param ywid
     * @param newId
     * @return
     * @throws Exception
     */
    private HttpResult updateMultipleJsydJbxx(List<CoordinateFile> coordinateFiles,String ywid,String newId,String yhid) throws Exception{
        List<Map> dataList = new ArrayList<>();
        for(CoordinateFile coordinateFile : coordinateFiles){
            Map<String,Object> data = coordinateFile.getAllAttribute();
            dataList.add(data);
        }
        Map<String,Object> param = new HashMap<>();
        param.put("acc_token","acc_token");
        param.put("data",dataList);
        param.put("newId",newId);
        param.put("yhid","9999");
        param.put("ywid",ywid);
        log.info("参数：{}",objectMapper.writeValueAsString(param));
        HttpResult httpResult = httpAPIService.doPostByJsonParam(updateMultipleJsydJbxxUrl,objectMapper.writeValueAsString(param));
        return httpResult;
    }

}
